package org.gim.controller;


import dev.langchain4j.data.document.Document;
import dev.langchain4j.data.document.loader.FileSystemDocumentLoader;
import dev.langchain4j.data.segment.TextSegment;
import dev.langchain4j.memory.ChatMemory;
import dev.langchain4j.memory.chat.MessageWindowChatMemory;
import dev.langchain4j.model.chat.StreamingChatModel;
import dev.langchain4j.model.chat.response.ChatResponse;
import dev.langchain4j.model.chat.response.StreamingChatResponseHandler;
import dev.langchain4j.model.openai.OpenAiChatModel;
import dev.langchain4j.model.openai.OpenAiStreamingChatModel;
import dev.langchain4j.rag.content.retriever.EmbeddingStoreContentRetriever;
import dev.langchain4j.service.AiServices;
import dev.langchain4j.store.embedding.EmbeddingStoreIngestor;
import dev.langchain4j.store.embedding.inmemory.InMemoryEmbeddingStore;
import org.gim.common.CommonResult;
//import org.heart.controller.excel.ExcelParserService;
import org.gim.config.batch.*;
import org.gim.entity.dto.TestDto;
import org.gim.thirdService.AIServiceAPI.service.AisServices;
import org.gim.thirdService.AIServiceAPI.tools.WeatherTool;
import org.gim.thirdService.KnowledgeService.service.DocumentIngestService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

import java.io.File;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

import static dev.langchain4j.model.openai.OpenAiChatModelName.GPT_3_5_TURBO;

@RequestMapping("/api")
@RestController
public class TestController {

    private static final Logger log = LoggerFactory.getLogger(TestController.class);

    @Resource
    private OpenAiChatModel openAiChatModel;

    @Resource
    private WangYiNewsDataBath wangYiNewsDataBath;

    @Resource
    private CSDNNewsDataBatch csdnNewsDataBatch;

    @Resource
    private PengPaiNewsDataBatch pengPaiNewsDataBatch;

    @Resource
    private XinLangNewsDataBatch xinLangNewsDataBatch;

    @Resource
    private DouYinNewsDataBatch douYinNewsDataBatch;

    @Resource
    private XinLangFinanceDataBatch xinLangFinanceDataBatch;

    @Resource
    private DocumentIngestService documentIngestService;

    @GetMapping("/queryState")
    public CommonResult<String> queryState() {

//        String userAskInfo = "帮我介绍一下【心中之温】是一个项目项目?";
        String userAskInfo = "帮我介绍一下【心中之温】是一个项目项目?";
        String documents = documentIngestService.queryFromQdrantAndIntegrate("Gim_mi0kmgyyvd",userAskInfo);

        AisServices assistant = AiServices.builder(AisServices.class)
                .chatModel(openAiChatModel)
                .build();

        log.info("用户需求为：{}",userAskInfo);

        log.info("相关知识文档为：{}",documents);

        String info = assistant.chat1(userAskInfo);

        log.info("info=={}",info);

        return CommonResult.successResponse("健康实例！");
    }

    @GetMapping("/aiAsk")
    public String aiAsk() {

        String userAskInfo = "帮我介绍一下【心中之温】是一个项目项目?";
        String documents = documentIngestService.queryFromQdrantAndIntegrate("Gim_mdq6ad1j43k",userAskInfo);

        AisServices assistant = AiServices.builder(AisServices.class)
                .chatModel(openAiChatModel)
                .build();

        log.info("用户需求为：{}",userAskInfo);

        log.info("相关知识文档为：{}",documents);

        String prompt =
                "根据以下用户需求和相关知识文档，帮我生成一段清晰、简明的中文介绍。" +
                        "\n\n用户需求:\n" + userAskInfo +
                        "\n\n相关知识文档:\n" + documents +
                        "\n\n要求:\n" +
                        "1. 结合知识文档回答，不要编造信息。\n" +
                        "2. 回答要逻辑清晰，条理分明，便于理解。\n" +
                        "3. 输出语言为中文。\n" +
                        "4. 尽量精简，不需要重复内容。\n\n" +
                        "请根据上面的内容生成回答:";



        String answer = assistant.chat1(prompt);

        System.out.println(answer);

        return answer;
    }

    @GetMapping("/runTaskService1")
    public CommonResult<String> runTaskService1() {

        log.info("请求接口 '/api/test'");

//        wangYiNewsDataBath.runTask();

//        csdnNewsDataBatch.runTask();

//            pengPaiNewsDataBatch.runTask();
//        xinLangNewsDataBatch.runTask();

//        douYinNewsDataBatch.runTask();

        xinLangFinanceDataBatch.runTask();

        return CommonResult.successResponse("健康实例！");
    }

    public void change(String s,AtomicBoolean s1,StringBuilder s2,Boolean ok){
        s = s+"12";
        s1.set(false);
        s2.append("456");
        ok = false;
    }





    /**
     * 集成 RAG 系统
     *
     * 从文件系统中 读取文件信息
     */
    @GetMapping("/testRag")
    public CommonResult<String> integrationRag(@RequestParam("city") String city) {

        String projectRootPath = new File("").getAbsolutePath();
        String filePath = projectRootPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static";

        List<Document> documents = FileSystemDocumentLoader.loadDocuments(filePath);
        InMemoryEmbeddingStore<TextSegment> embeddingStore = new InMemoryEmbeddingStore<>();
        System.out.println("embeddingStore=="+embeddingStore);

        EmbeddingStoreIngestor.ingest(documents, embeddingStore);

        System.out.println("embeddingStore=="+embeddingStore);

        AisServices assistant = AiServices.builder(AisServices.class)
                .chatModel(openAiChatModel)
                .contentRetriever(EmbeddingStoreContentRetriever.from(embeddingStore))
                .build();


        String message = assistant.chat1(
                "请从数据中精确查询 `location_name_zh` 字段值为 '" + city + "' 的城市记录，并返回以下信息：\n"
                        + "location_id 值,"
        );
        return CommonResult.successResponse(message);
    }

    public static void main(String[] args) {
        String projectRootPath = new File("").getAbsolutePath();

        String filePath = projectRootPath + File.separator + "src" + File.separator + "main" + File.separator + "resources" + File.separator + "static" + File.separator + "cityCodeList.xls";

        System.out.println(filePath);

    }
}
